package com.lwt.service.impl;

import com.lwt.mapper.CommentMapper;
import com.lwt.po.Comment;
import com.lwt.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: blog
 * @author: 关键我是大怪
 * @create: 2021-08-02 14:48
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        //查询出父节点
        List<Comment> comments = commentMapper.findComment(blogId, Long.parseLong("-1"));
        for (Comment comment : comments) {
            Long id = comment.getId();
            String parentNickname1 = comment.getNickname();
            List<Comment> chiledComment = commentMapper.findComment(blogId, id);
            //查询子评论
            combineChildren(blogId, chiledComment, parentNickname1);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();

        }

        return comments;
    }

    private void combineChildren(Long blogId, List<Comment> childComments, String parentNickname1) {
//        判断是否有一级子评论
        if (childComments.size() > 0) {
//                循环找出子评论的id
            for (Comment childComment : childComments) {
                String parentNickname = childComment.getNickname();
                childComment.setParentNickname(parentNickname1);
                tempReplys.add(childComment);
                Long childId = childComment.getId();
                List<Comment> comment = commentMapper.findComment(blogId, childId);
//                    查询出子二级评论
                combineChildren(blogId, comment, parentNickname);
            }
        }
    }

    //    新增评论
    @Override
    public int saveComment(Comment comment) {
        comment.setCreateTime(new Date());
        int comments = commentMapper.saveComment(comment);
        return comments;
    }

    //删除评论
    @Override
    public void deleteComment(Comment comment, Long id) {
        Long blogId = comment.getBlogId();
        deletechild(blogId, id);
        commentMapper.deleteComment(id);
    }

    //删除子评论
    private void deletechild(Long blogId, Long id) {
        List<Comment> comments = commentMapper.findComment(blogId, id);
        if (comments.size() > 0) {
            for (Comment comment : comments) {
                Long id1 = comment.getId();
                deletechild(blogId, id1);
                commentMapper.deleteComment(id1);
            }
        }
    }
}

